/*
 * downloadManager.cc
 *
 *  Created on: May 3, 2011
 *      Author: xrose
 */

#include "incdefault.h"
#include "download2.h"

using namespace std;

int main( int argc, char *argv[]){

	char url[MAX_STR_LEN]; // url of the file to be downloaded
	int num_of_threads = 5;
	int download_status;

	if(argc < 3){//at least three argument is required
		cout<<"\nUSAGE: download.exe [-d] | [-n] [-u] <URL>"<<endl;
		cout<<"OPTIONS:\n"<<endl;
		cout<<"\t-n: an integer specifying the number of downloading threads."<<endl;
		cout<<"\t-d: Downloads all links with depth 1 from the specified URL"<<endl;
		cout<<"\t-u: Downloads a target file from the specified URL"<<endl;
		exit(ERROR);
	}
	else{
		if( (strcmp( argv[1], "-u") == 0) || ( strcmp( argv[1], "-U") == 0) ){
			/* download binary )file with default number of treats*/
			if(argc > 3){
				cout<<"ERROR: More argument passing...!"<<endl;
				exit(ERROR);
			}
			strcpy( url, argv[2] );

			string str_url(url);
			cout<<"DEBUG: download-manager"<<endl;
			download_status = downloadFile(str_url, num_of_threads);
			if (download_status == SUCCESS) printf("\n:::Download Completed:::\n");

		}else if( ( strcmp( argv[1], "-d") == 0 ) || ( strcmp( argv[1], "-D") == 0) ){
			/* download webpage*/
			if(argc > 3){cout <<"File name :" << url << endl;
				cout<<"\nERROR: More argument passing...!"<<endl;
				exit(ERROR);
			}

			string url(argv[2]);
 			download_status = download_links(url);
		}else if( (strcmp( argv[1], "-n") == 0) || ( strcmp( argv[1], "-N") == 0) ){
			/* download binary file according to taken treat number */
			if(argc != 5){
				cout<<"ERROR: Incompitable argument passing...!"<<endl;
				exit(ERROR);
			}
			if( (strcmp( argv[3], "-u"  ) ==0 )||(strcmp( argv[3], "-U"  ) ==0 ) ){
				num_of_threads = atoi(argv[2]);
				if (num_of_threads < 1)
				{
					cout<<"ERROR: Negative number for parameter -n"<<endl;
					return ERROR;
				}
				strcpy( url, argv[4] );

				string str_url(url);

				download_status = downloadFile(str_url, num_of_threads);
				if (download_status == SUCCESS) cout<<":::Download Completed:::"<<endl;
			}else{
				cout<<"ERROR: Incompitable argument passing...!"<<endl;
				exit(ERROR);
			}
		}
	}

	return(download_status);

}
